package com.nep.NEPM.controller;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.FileChooser;
import com.nep.NEPM.Data.AQILevelData;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class AQIController {

    @FXML private TableView<AQILevelData> aqiTableView;
    @FXML private TableColumn<AQILevelData, String> levelColumn;
    @FXML private TableColumn<AQILevelData, String> descriptionColumn;
    @FXML private TableColumn<AQILevelData, Integer> countColumn;

    private final ObservableList<AQILevelData> data = FXCollections.observableArrayList();

    @FXML
    public void initialize() {
        // 设置列与模型属性的映射
        levelColumn.setCellValueFactory(new PropertyValueFactory<>("level"));
        descriptionColumn.setCellValueFactory(new PropertyValueFactory<>("description"));
        countColumn.setCellValueFactory(new PropertyValueFactory<>("count"));

        // 初始加载数据
        aqiTableView.setItems(data);
    }

    // 文件选择器方法
    @FXML
    private void handleLoadFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择AQI数据文件");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("CSV文件", "*.csv"),
                new FileChooser.ExtensionFilter("文本文件", "*.txt"),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
        );

        File selectedFile = fileChooser.showOpenDialog(aqiTableView.getScene().getWindow());
        if (selectedFile != null) {
            loadDataFromFile(selectedFile);
        }
    }

    // 核心文件读取方法
    private void loadDataFromFile(File file) {
        data.clear(); // 清空现有数据

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            // 跳过CSV文件标题行
            // reader.readLine();

            while ((line = reader.readLine()) != null) {
                // 处理不同格式文件
                if (file.getName().endsWith(".csv")) {
                    parseCsvLine(line);
                } else {
                    parseTextLine(line);
                }
            }
        } catch (Exception e) {
            // 显示友好的错误提示
            showErrorAlert("文件加载错误", "加载文件时出现错误: " + e.getMessage());
        }
    }

    // 解析CSV格式文件
    private void parseCsvLine(String line) {
        String[] parts = line.split(",");
        if (parts.length >= 3) {
            try {
                data.add(new AQILevelData(
                        parts[0].trim(),
                        parts[1].trim(),
                        Integer.parseInt(parts[2].trim())
                ));
            } catch (NumberFormatException e) {
                showErrorAlert("数据格式错误", "CSV文件中存在无效的数字格式: " + line);
            }
        } else {
            showErrorAlert("数据格式错误", "CSV文件中存在无效的行: " + line);
        }
    }

    // 解析自定义文本格式文件
    private void parseTextLine(String line) {
        // 示例格式：一级|优|1580
        String[] parts = line.split("\\|");
        if (parts.length == 3) {
            try {
                data.add(new AQILevelData(
                        parts[0].trim(),
                        parts[1].trim(),
                        Integer.parseInt(parts[2].trim())
                ));
            } catch (NumberFormatException e) {
                showErrorAlert("数据格式错误", "文本文件中存在无效的数字格式: " + line);
            }
        } else {
            showErrorAlert("数据格式错误", "文本文件中存在无效的行: " + line);
        }
    }

    // 显示错误警告框
    private void showErrorAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    public static class AQIData {
        private final String level;
        private final String description;
        private final int count;

        public AQIData(String level, String description, int count) {
            this.level = level;
            this.description = description;
            this.count = count;
        }

        // 添加新的构造函数
        public AQIData(int level, String description, int count) {
            this.level = String.valueOf(level);
            this.description = description;
            this.count = count;
        }

        public String getLevel() { return level; }
        public String getDescription() { return description; }
        public int getCount() { return count; }
    }
}